package com.neusoft.elmboot.po;

import java.util.HashMap;
import java.util.Map;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Properties;

import com.neusoft.elmboot.service.impl.InsufficientBalanceException;
import com.neusoft.elmboot.util.CommonUtil;

// 定义了一个表示虚拟钱包的领域模型类


public class VirtualWallet {
    
    
	// 钱包的唯一标识符
    private Long walletId;
	// 钱包的创建时间，默认为当前时间
    private String createTime = CommonUtil.getCurrentDate();
    // 钱包的余额，默认为0
    private BigDecimal balance = BigDecimal.ZERO;
    // 奖励规则，默认为空
    private Map<BigDecimal, BigDecimal> rewardRules;
    //用户账号
    private String userId;
    //透支金额
    private BigDecimal overdraftAmount = BigDecimal.ZERO;
    //利息
    private BigDecimal interest = BigDecimal.ZERO;
    // 利率（例如：年化利率为5%，则此处为0.05）
    private static final BigDecimal INTEREST_RATE = new BigDecimal("0.05");
   

    // 构造函数，接受一个预分配的ID作为参数
    public VirtualWallet(String userId) {
        this.userId = userId;
        loadRewardRules(); // 加载奖励规则
    }

    // 获取钱包余额的方法
    public BigDecimal balance() {
        return this.balance;
    }

    //获取透支金额
    public BigDecimal OverdraftAmount() {
        return overdraftAmount;
    }

    // 从钱包中扣除指定金额的方法
    public void debit(BigDecimal amount) {
        // 如果钱包余额不足以扣除指定金额，则抛出异常
        if (this.balance.compareTo(amount) < 0) {
            throw new IllegalArgumentException("Debit amount must be positive.");

        }
        // 扣除指定金额
        this.balance=this.balance.subtract(amount);
      
    }

    // 向钱包中增加指定金额的方法
    public void credit(BigDecimal amount) {
        // 如果增加的金额为负数，则抛出异常
        if (amount.compareTo(BigDecimal.ZERO) < 0) {
            throw new IllegalArgumentException("Credit amount must be positive.");
        }
        // 增加指定金额
        this.balance=this.balance.add(amount);
    }

    public void unfreeze(BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("Unfreeze amount must be positive.");
        }
        this.balance=this.balance.add(amount);
    }

     // 充值方法
    public void deposit(BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("Deposit amount must be positive.");
        }
        BigDecimal bonus = calculateBonus(amount);
        balance = this.balance.add(amount).add(bonus);
    }

    //提现方法，应该有手续费
    public void withdraw(BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) <= 0) {
            throw new IllegalArgumentException("Withdraw amount must be positive.");
        }
        if (this.balance.compareTo(amount) < 0) {
            throw new IllegalArgumentException("Insufficient balance.");
        }
        //计算手续费
        BigDecimal fee = amount.multiply(new BigDecimal("0.05"));
        // System.out.println("手续费为"+fee);
        // System.out.println(this.balance);
        this.balance=this.balance.subtract(amount).subtract(fee);
        // System.out.println(this.balance);
        //还有扣除手续费

    }

    //加载奖励规则
    private void loadRewardRules() {
        Properties props = new Properties();
        try (InputStream is = getClass().getClassLoader().getResourceAsStream("reward-rules.properties")) {
            if (is != null) {
                props.load(is);
                rewardRules = new HashMap<>();
                for (String key : props.stringPropertyNames()) {
                    if (key.startsWith("threshold")) {
                        rewardRules.put(new BigDecimal(props.getProperty(key)), new BigDecimal(props.getProperty(key.replace("threshold", "bonus"))));
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 计算利息的方法
    public BigDecimal calculateInterest( BigDecimal overdraftAmount,Integer repaymentDeadline) {
        if (overdraftAmount != null && repaymentDeadline != null) {
            BigDecimal years = new BigDecimal(repaymentDeadline).divide(new BigDecimal(30), 2, RoundingMode.HALF_UP);
            interest = overdraftAmount.multiply(INTEREST_RATE).multiply(years);
            return interest;
        }
        return null;
    }

    // 计算充值奖励的方法
    private BigDecimal calculateBonus(BigDecimal depositAmount) {
        if (rewardRules == null || rewardRules.isEmpty()) {
            return BigDecimal.ZERO;
        }

        for (Map.Entry<BigDecimal, BigDecimal> entry : rewardRules.entrySet()) {
            if (depositAmount.compareTo(entry.getKey()) >= 0) {
                return entry.getValue();
            }
        }
        return BigDecimal.ZERO;
    }

     // 增加透支金额的方法
     public void increaseOverdraftAmount(BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) > 0) {
            this.overdraftAmount = this.overdraftAmount.add(amount);
        }
    }

    // 减少透支金额的方法
    public void decreaseOverdraftAmount(BigDecimal amount) {
        if (amount.compareTo(BigDecimal.ZERO) > 0) {
            this.overdraftAmount = this.overdraftAmount.subtract(amount);
        }
    }

    public Long getWalletId() {
		return walletId;
	}

	public void setWalletId(Long walletId) {
		this.walletId = walletId;
	}

	public String getCreateTime() {
		return createTime;
	}

	public void setCreateTime(String createTime) {
		this.createTime = createTime;
	}

	public BigDecimal getBalance() {
		return balance;
	}

	public void setBalance(BigDecimal balance) {
		this.balance = balance;
	}

	public Map<BigDecimal, BigDecimal> getRewardRules() {
		return rewardRules;
	}

	public void setRewardRules(Map<BigDecimal, BigDecimal> rewardRules) {
		this.rewardRules = rewardRules;
	}

	public String getUserId() {
		return userId;
	}

	public void setUserId(String userId) {
		this.userId = userId;
	}

    public BigDecimal getOverdraftAmount() {
        return overdraftAmount;
    }

    public void setOverdraftAmount(BigDecimal overdraftAmount) {
        this.overdraftAmount = overdraftAmount;
    }
	
}